package com.jgp.security.service;

import com.jgp.common.utils.JGPUtil;
import com.jgp.security.secmodel.DataPowerType;
import com.jgp.security.secmodel.SecGivePower;
import com.jgp.security.secrepository.SecGivePowerRepository;
import com.jgp.sys.query.Operator;
import com.jgp.sys.query.QueryFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2022/2/18
 */
@Service
@CacheConfig(cacheNames = "GIVE-POWER-SERVICE")
@Transactional(transactionManager = "secondTransactionManager", readOnly = true)
public class SecGivePowerService {
	
	@Autowired
	private SecGivePowerRepository repository;
	
	@CacheEvict(key = "#userId", allEntries = true)
	@Transactional(transactionManager = "secondTransactionManager")
	public void grantAuthorizationWithInstitution(List<String> institutionIds, String userId) {
		
		List<SecGivePower> oldPowers = queryAuthorizationWithInstitution(userId);
		
		List<String> oldInstitutionIds = oldPowers.stream().map(SecGivePower::getProvider).collect(Collectors.toList());
		List<String> intersections = JGPUtil.intersection(oldInstitutionIds,institutionIds);
		List<String> differences = JGPUtil.difference(oldInstitutionIds,institutionIds);
		
		//删掉多余的项
		if(differences.size()>0){
			QueryFilterList delFilters = new QueryFilterList();
			delFilters.addFilter("provider", Operator.in, differences);
			delFilters.addFilter("receiver", Operator.eq, userId + "");
			delFilters.addFilter("receiverType", Operator.eq, DataPowerType.PERSON);
			delFilters.addFilter("providerType", Operator.eq, DataPowerType.ORG);
			repository.deletePersist(delFilters);
		}
		
		List<SecGivePower> powers = new ArrayList<>();
		
		for (String institutionId : institutionIds) {
			if (!intersections.contains(institutionId)) {
				SecGivePower power = new SecGivePower();
				power.setProvider(institutionId + "");
				power.setProviderType(DataPowerType.ORG);
				power.setReceiver(userId + "");
				power.setReceiverType(DataPowerType.PERSON);
				powers.add(power);
			}
		}
		repository.createInBatch(powers);
	}
	
	@Cacheable(key = "#userId")
	public List<SecGivePower> queryAuthorizationWithInstitution(String userId) {
		QueryFilterList filters = new QueryFilterList();
		filters.addFilter("receiver", Operator.eq, userId + "");
		filters.addFilter("receiverType", Operator.eq, DataPowerType.PERSON);
		filters.addFilter("providerType", Operator.eq, DataPowerType.ORG);
		return repository.read(filters);
	}
}
